﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Text.RegularExpressions;

namespace StatisticsBadRatio.Common
{
    public class BusinessProcess
    {
        static Regex fileRegex;
        /// <summary>
        /// 序列化XML文件
        /// </summary>
        /// <param name="path">the path to save the xml file</param>
        /// <param name="obj">the object you want to serialize</param>
        public static void SerializeToXml<T>(string path, T obj) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            string content = string.Empty;
            //serialize
            using (StringWriter writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);
                content = writer.ToString();
            }
            //save to file
            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.Read))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(content);
                }
            }
        }
        /// <summary>
        /// 反序列XML文件
        /// </summary>
        /// <param name="path">the path of the xml file</param>
        /// <param name="object_type">the object type you want to deserialize</param>
        public static T DeserializeFromXml<T>(string path) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StreamReader reader = new StreamReader(path))
            {
                return serializer.Deserialize(reader) as T;
            }
        }
        /// <summary>
        /// 获取文件夹下面的所有文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="list">目标文件集合</param>
        public static void GetFiles(string path,ref List<string> list)
        {
            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(path);
                foreach (var fInfo in directoryInfo.GetFiles())
                {
                    fileRegex = new Regex(Global.AppConfigs.DataSourceFileSearchFormat);
                    if (fileRegex.IsMatch(fInfo.Name))
                    {
                        int count = list.Count(x => x.Substring(x.LastIndexOf("\\") + 1) == fInfo.Name);
                        if (count<=0)
                        {
                            list.Add(fInfo.FullName);
                        }
                    }
                }
                foreach (var dInfo in directoryInfo.GetDirectories())
                {
                    GetFiles(dInfo.FullName, ref list);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}
